<template>
  <div class="home-box" style="margin-left: 20px">
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="岗位名称">
        <el-input
          v-model="searchForm.position"
          placeholder="岗位名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="部门名称">
        <el-input
          v-model="searchForm.dept"
          placeholder="部门名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchEvent" type="primary">查询 </el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="update" type="primary">重置 </el-button>
      </el-form-item>
      <el-form-item>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button circle icon="Refresh" @click="update" />
        </el-tooltip>
      </el-form-item>
    </el-form>
  </div>
  <el-button
    type="primary"
    plain
    icon="Plus"
    @click="handleAdd"
    style="margin-left: 20px"
    >新增</el-button
  >
  <el-button
    color="#626aef"
    :dark="isDark"
    plain
    icon="Upload"
    @click="handleUP"
    >导入岗位</el-button
  >
  <el-button
    color="#626aef"
    :dark="isDark"
    plain
    icon="Upload"
    @click="handleUP1"
    >导入岗位-评分</el-button
  >
  <el-button
    color="#626aef"
    :dark="isDark"
    plain
    icon="Upload"
    @click="handleUP2"
    >导入岗位-计件</el-button
  >
  <el-button
    color="#626aef"
    :dark="isDark"
    plain
    icon="Upload"
    @click="handleUP3"
    >导入岗位-提成</el-button
  >
  <el-button type="success" plain icon="Check" @click="handleNew"
    >更新岗位考核状态</el-button
  >
  <!--<el-button color="#626aef" :dark="isDark" plain icon="Download" @click="handleOut"
    >导出</el-button
  >-->
  <el-table
    :data="PositionList"
    style="
      width: 98%;
      margin: 20px;
      border-radius: 5px;
      box-shadow: 5px 5px 10px rgba(64, 158, 255, 0.5);
    "
    size="large"
    :header-cell-style="{
      background: '#337ecc !important',
      color: '#ffffff',
      border: 'none !important',
    }"
    element-loading-text="加载中..."
  >
    <el-table-column
      prop="position"
      label="岗位名称"
      width="120"
      class-name="my-content"
    >
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>备注：{{ scope.row.ins }}</div>
          </template>
          <template #reference>
            {{ scope.row.position }}
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="typeName" label="岗位类型" width="120" />
    <el-table-column prop="deptName" label="所属部门" width="120" />
    <el-table-column prop="state" label="状态" width="80">
      <template #default="scope">
        <el-tag
          :type="scope.row.state === 1 ? 'success' : 'dange'"
          disable-transitions
          >{{ scope.row.state === 0 ? "未启用" : "启用" }}</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="最后更新时间" width="220">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <el-icon><timer /></el-icon>
          <span>{{ scope.row.updateTime }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="auditStatus" label="考核状态" width="110">
      <template #default="scope">
        <el-tag
          :type="scope.row.auditStatus === 0 ? 'info' : 
          (scope.row.auditStatus === 1 ? 'primary' :
          (scope.row.auditStatus === 2 ? 'warning' :
          (scope.row.auditStatus === 3 ? 'success' :'danger')))"
          disable-transitions
          >{{
            scope.row.auditStatus === 0? "未考核": 
            (scope.row.auditStatus === 1? "考核中": 
            (scope.row.auditStatus === 2? "暂停": 
            (scope.row.auditStatus === 3? "考核完成": "未知")))
          }}</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          @click="onShowClick(scope.row)"
          round
          v-show="scope.row.auditStatus === 0||scope.row.auditStatus === 3"
          color="#337ECC"
          >绩效管理</el-button
        >
        <el-button
          @click="handleEdit(scope.$index, scope.row)"
          round
          v-show="scope.row.auditStatus === 0"
          >编辑</el-button
        >
        <el-button
          round
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          v-show="scope.row.auditStatus === 0 || scope.row.auditStatus === 2"
          >删除</el-button
        >
        <el-button
          round
          type="success"
          @click="startPositionFlow(scope.$index, scope.row)"
          v-show="scope.row.auditStatus === 0 && scope.row.type != 2"
          >开始考核</el-button
        >
        <el-button
          round
          type="warning"
          @click="handleStop(scope.$index, scope.row)"
          v-show="scope.row.auditStatus === 1"
          >暂停</el-button
        >
        <el-button
          round
          type="success"
          @click="handleRestore(scope.$index, scope.row)"
          v-show="scope.row.auditStatus === 2"
          >恢复</el-button
        >
        <el-button
          round
          type="danger"
          @click="handleRemove(scope.$index, scope.row)"
          v-show="scope.row.auditStatus === 2 || scope.row.auditStatus === 1"
          >结束考核</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <pagination
    class="pagination"
    v-show="PositionPage.total > 0"
    :total="PositionPage.total"
    v-model:page="searchForm.page"
    v-model:limit="PositionPage.size"
    @pagination="handlePagination"
  />
  <Dialog2
    v-model="dialog_2Visible"
    :close="close"
    :update="update"
    :editForm="editForm"
    :type="type"
    :title="title"
  ></Dialog2>
  <UploadExcel
    v-model="upload.open"
    :title="upload.upLoadTitle"
    :url="importUrl"
    :tipShow="true"
    @onSuccess="onSuccess"
    @onDownTemplate="onDownTemplate"
  ></UploadExcel>
  <ScoreExcel
    v-model="upload1.open"
    :title="upload1.upLoadTitle"
    :url="importUrl1"
    :tipShow="true"
    @onSuccess="onSuccess1"
    @onDownTemplate="onDownTemplate1"
  >
  </ScoreExcel>
  <PieceExcel
    v-model="upload2.open"
    :title="upload2.upLoadTitle"
    :url="importUrl2"
    :tipShow="true"
    @onSuccess="onSuccess2"
    @onDownTemplate="onDownTemplate2"
  >
  </PieceExcel>
  <KpiExcel
    v-model="upload3.open"
    :title="upload3.upLoadTitle"
    :url="importUrl3"
    :tipShow="true"
    @onSuccess="onSuccess3"
    @onDownTemplate="onDownTemplate3"
  >
  </KpiExcel>
</template>
<script setup>
import { ref, onMounted, onBeforeMount, reactive, watch } from "vue";
import { Timer } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import Dialog2 from "./components/Dialog_2";
import { getPositionPage, startFlow } from "@/api/api";
import { stopFlow, restoreFlow, deleteFlow } from "@/api/task";
import { updateState, searchPosition, deletePosition } from "@/api/position";
import { ElMessage, ElMessageBox } from "element-plus";
import UploadExcel from "@/components/SendAndDownload/index";
import ScoreExcel from "@/components/SendAndDownload/index";
import PieceExcel from "@/components/SendAndDownload/index";
import KpiExcel from "@/components/SendAndDownload/index";
import {
  getPositionTemplate,
  getPositionScoreTemplate,
  getPositionPieceTemplate,
  getPositionKpiTemplate,
} from "@/api/template";
import store from '@/store'

const searchForm = ref({
  position: "",
  dept:"",
  page: 1,
  page_size: 10,
});

const PositionPage = ref([]);
const PositionList = ref([]);
onBeforeMount(() => {
  if(store.getters.position)
    searchForm.value.position=store.getters.position
  if(store.getters.page_size)
    searchForm.value.page_size=store.getters.page_size
  if(store.getters.page)
    searchForm.value.page=store.getters.page
  if(store.getters.dept)
    searchForm.value.dept=store.getters.dept
  searchPosition(searchForm.value).then((data) => {
    PositionPage.value = data.data;
    PositionList.value = data.data.records;
  });
});
watch(
  PositionList,
  (newVal) => {
    console.log("list发生了改变");
  },
  { deep: true }
);

const handlePagination = (value) => {
  if (searchForm.value.position == ""&&searchForm.value.dept == "") {
    getPositionPage(value).then((data) => {
      PositionPage.value = data.data;
      PositionList.value = data.data.records;
    });
  } else {
    searchForm.value.page = value.page;
    searchForm.value.page_size = value.page_size;
    searchPosition(searchForm.value).then((data) => {
      PositionPage.value = data.data;
      PositionList.value = data.data.records;
    });
  }
};

const searchEvent = () => {
  searchPosition(searchForm.value).then((data) => {
    PositionPage.value = data.data;
    PositionList.value = data.data.records;
  });
};

const importUrl = ref("/Position/upload");
const upload = ref({
  open: false,
  upLoadTitle: "岗位上传",
});
const onSuccess = (res) => {
  upload.value.open = false;
};
const handleUP = () => {
  upload.value.open = true;
};
const onDownTemplate = () => {
  getPositionTemplate();
};

const importUrl1 = ref("/ScoreRule/uploadPosition");
const upload1 = ref({
  open: false,
  upLoadTitle: "岗位-评分上传",
});
const onSuccess1 = (res) => {
  upload1.value.open = false;
};
const handleUP1 = () => {
  upload1.value.open = true;
};
const onDownTemplate1 = () => {
  getPositionScoreTemplate();
};

const importUrl2 = ref("/PieceRule/uploadPosition");
const upload2 = ref({
  open: false,
  upLoadTitle: "岗位-评分上传",
});
const onSuccess2 = (res) => {
  upload2.value.open = false;
};
const handleUP2 = () => {
  upload2.value.open = true;
};
const onDownTemplate2 = () => {
  getPositionPieceTemplate();
};

const importUrl3 = ref("/KpiRule/uploadPosition");
const upload3 = ref({
  open: false,
  upLoadTitle: "岗位-提成上传",
});
const onSuccess3 = (res) => {
  upload3.value.open = false;
};
const handleUP3 = () => {
  upload3.value.open = true;
};
const onDownTemplate3 = () => {
  getPositionKpiTemplate();
};

const editForm = ref([]);
const title = ref("新增岗位");
const type = ref("add");
const dialog_2Visible = ref(false);
const handleAdd = (row) => {
  title.value = "新增岗位";
  type.value = "add";
  dialog_2Visible.value = true;
  editForm.value = {
    id: "",
    position: "",
    secondName: "",
    secondId: "",
    thirdName: "",
    thirdId: "",
    fourthName: "",
    fourthId: "",
    positionType: "",
    state: true,
    ins: "",
    auditStatus: 0,
  };
};
const handleEdit = (index, row) => {
  title.value = "编辑岗位";
  type.value = "edit";
  dialog_2Visible.value = true;
  editForm.value = row;
};
const handleDelete = (index, row) => {
  let id = row.id;
  deletePosition({ id }).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      update();
    } else {
      ElMessage.error("删除失败");
    }
  });
};

const router = useRouter();
const onShowClick = (row) => {
  store.dispatch('skip/beforeSet',searchForm)
  router.push({
    path: "/performSet/edit",
    query: row,
  });
};

const startPositionFlow = (index, row) => {
  let positionId = row.id;
  let empId = JSON.parse(localStorage.getItem("userInfo")).id;
  let type = row.type;
  startFlow({ positionId, empId, type }).then((data) => {
    console.log(data);
    if (data.code == 200) {
      ElMessage({
        message: "发布成功",
        type: "success",
      });
      PositionList.value[index].auditStatus = 1;
    } else {
      ElMessage.error("发布失败");
      ElMessageBox.confirm(
        "该岗位未配置对应的审核人与审核时限，请前往配置",
        "操作失败",
        {
          confirmButtonText: "前往配置",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          router.push({
            path: "/performSet/assessorTimer",
          });
        })
        .catch(() => {});
    }
  });
};

const handleStop = (index, row) => {
  let positionId = row.id;
  stopFlow({ positionId }).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "暂停成功",
        type: "success",
      });
      PositionList.value[index].auditStatus = 2;
    } else {
      ElMessage.error("暂停失败");
    }
  });
};

const handleRestore = (index, row) => {
  let positionId = row.id;
  restoreFlow({ positionId }).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "恢复成功",
        type: "success",
      });
      PositionList.value[index].auditStatus = 1;
    } else {
      ElMessage.error("恢复失败");
    }
  });
};

const handleRemove = (index, row) => {
  let positionId = row.id;
  deleteFlow({ positionId }).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "结束考核成功",
        type: "success",
      });
      update();
    } else {
      ElMessage.error("结束考核失败");
    }
  });
};

const handleNew = () => {
  ElMessageBox.confirm(
    "将开启新一个月的绩效考核流程，请确认上一个月的绩效考核已完成",
    "注意",
    {
      cancelButtonText: "取消",
      confirmButtonText: "确认",
      type: "warning",
    }
  )
    .then(() => {
      ElMessage({
        type: "success",
        message: "成功开启新一个月的绩效考核流程",
      });
      updateState().then((data) => {
        if (data.code == 200) {
          ElMessage({
            message: "更新岗位管理状态成功",
            type: "success",
          });
          update();
        } else {
          ElMessage.error("更新岗位管理状态失败");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};

const close = () => {
  dialog_2Visible.value = false;
};
const update = () => {
  searchForm.value.position = "";
  searchForm.value.dept = "";
  store.dispatch('skip/clear')
  getPositionPage(searchForm.value).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "更新成功",
        type: "success",
      });
      PositionPage.value = data.data;
      PositionList.value = data.data.records;
    } else {
      ElMessage.error("更新失败");
    }
  });
};
</script>

<style lang="scss" scoped>
:deep(.my-content) {
  background: #ecf5ff !important;
  font-size: 15px;
}
.pagination {
  margin: 20px 20px;
  display: flex;
  justify-content: end;
}
</style>
